'use strict';

/* Controllers */
app.controller('houseOwnerMenuNodeCtl', function($scope, $http, rest, $compile, $location, ngDialog, user, $state, $window, uiLoad, $rootScope, $ocLazyLoad, $timeout) {

    var token = $window.localStorage.getItem("token");
    
    //方法级权限
    var accessStr = $window.localStorage.getItem("accessStr");
    $scope.btns = {
    	add: 'innjia',  //新建
    	delete: 'innjia',  //删除
    	edit: 'innjia',  //编辑
    	jurisdiction: 'innjia',  //权限分配
    	resetPasswords: 'innjia',  //重置密码
    	addmember: 'innjia',  //添加成员
    	exportExcel: 'innjia', //导出表格
    	batchExportImg: 'innjia',  //批量导出图片
    	details: 'innjia',  //详情
    	rent: 'innjia',  //租赁PDF
    	list: 'innjia'  //列表
    }
    //延迟执行 - 当左侧菜单生产完毕再获取当前菜单的ID 利用ui-sref-active有且只有一个active即当前的特性用jq去获取预先存储在菜单上的id
    user.response().then(function(res){
    	var nowId = $(document).find(".navItem.active").attr("data-id");
    	rest.decoJava({
		   	 type: "post",
		     url: "/tenancy-sys/admin/menu/detail/"+nowId,
		     data: "",
		     //contentType:"application/json",
		     beforeSend: function(request){
				request.setRequestHeader("token", token); 
			},
		    success: function(data){ 
		    	console.log(data)
			    if(data.code == "0000"){
				    //匹配权限
				    angular.forEach(data.result.menuMethods,function(data){
				    	if(data.methodTagName == "add"){
				    		$scope.btns.add = data.id;
				    	} else if(data.methodTagName == "delete"){
				    		$scope.btns.delete = data.id;
				    	} else if(data.methodTagName == "edit"){
				    		$scope.btns.edit = data.id;
				    	} else if(data.methodTagName == "jurisdiction"){
				    		$scope.btns.jurisdiction = data.id;
				    	} else if(data.methodTagName == "resetPasswords"){
				    		$scope.btns.resetPasswords = data.id;
				    	} else if(data.methodTagName == "addmember"){
				    		$scope.btns.addmember = data.id;
				    	} else if(data.methodTagName == "exportExcel"){
				    		$scope.btns.exportExcel = data.id;
				    	} else if(data.methodTagName == "batchExportImg"){
				    		$scope.btns.batchExportImg = data.id;
				    	} else if(data.methodTagName == "details"){
				    		$scope.btns.details = data.id;
				    	} else if(data.methodTagName == "rent"){
				    		$scope.btns.rent = data.id;
				    	} else if(data.methodTagName == "list"){
				    		$scope.btns.list = data.id;
				    	}
				    })
			    } else if(data.message == "菜单Id有误！！！"){
			    	// $window.location.reload();
			    } else{
			    	layer.msg(data.message+'请刷新试试', {
			        	offset:'t',
			        	icon: 2
					});
			    }
		    }
	    });

    })
	
	//自定义方法状态数据
	$scope.methodsStatus = [
	        {
	            "status" : "AVAILABLE",
	            "menuName" : "可用"
	        },
	        {
	            "status" : "FORBID",
	            "menuName" : "禁止"
	        },
	        {
	            "status" : "DELETE",
	            "menuName" : "删除"
	        },
	        {
	            "status" : "",
	            "menuName" : "全部"
	        }
	    ];
	$scope.itemStatus = $scope.methodsStatus[0]; //默认为可用
	
    //初始化所属菜单
    rest.decoJava({
        type: "POST",
        url: "/tenancy-sys/admin/menu/all/list",
        data: '',
        //contentType:"application/json",
        beforeSend: function(request) {
            request.setRequestHeader("token", token);
        },
        success: function(data) {

            $scope.upMenus = [{
                menuName: "请选择",
                id: ""
            }];
            angular.forEach(data.result,function(item){
            	if(item.level==0){
            		$scope.upMenus.push(item);
            	}
            })
            
            $scope.upMenuName = $scope.upMenus[0];
        }
    });

    var tabHeight = ($window.innerHeight - 275) + "px"; //table内容区高度
    $scope.dataTableMenuedit = {
        "sAjaxSource": "/tenancy-sys/admin/menu/list",
        // "dom": "tipr",
        //"bFilter": true,  //搜索
        "sScrollY": tabHeight, //给定高度，内容超出即出滚动条
        "bScrollCollapse": false, //不管内容多少高度固定
        "aLengthMenu": [25, 50, 100, 200],
        "iDisplayLength": 25,
        "sDom": '<"top">rt<"bottom"lip><"clear">', //位置 l-每页显示数量,f-过滤输入,t-表单Table,i-信息,p-翻页
        "bAutoWidth": true,  //自适应列宽
        "aoColumns": [{
            "mDataProp": "",
            "sDefaultContent": "",
            "sClass": "center handle-ck"
        }, {
            "mDataProp": "menuName",
            "sTitle": "菜单名称",
            "sDefaultContent": "",
            "sClass": "center failure"
        }, {
            "mDataProp": "",
            "sTitle": "菜单等级",
            "sDefaultContent": "",
            "sClass": "center menu-grade"
        }, {
            "mDataProp": "upMenuName",
            "sTitle": "所属菜单",
            "sDefaultContent": "",
            "sClass": "center handle-upMenu"
        }, {
            "mDataProp": "menuPath",
            "sTitle": "跳转路径",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "sort",
            "sTitle": "排序",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "",
            "sTitle": "菜单类型",
            "sDefaultContent": "",
            "sClass": "center menuType"
        }, {
            "mDataProp": "",
            "sTitle": "菜单状态",
            "sDefaultContent": "",
            "sClass": "center menuStatus"
        }, {
            "mDataProp": "createTime",
            "sTitle": "创建时间",
            "sDefaultContent": "",
            "sClass": "center"
        }, {
            "mDataProp": "operate",
            "sTitle": "操作",
            "sDefaultContent": "",
            "sClass": "center handle-td"
        }],
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            var btnStr = "";
            btnStr += "<button type='button' class='btn-yellow' style='margin-right:10px;' data-btn='btns.edit' ng-click='menuedit(\"" + iDisplayIndex + "\",$event)'>编辑</button>";
            $(nRow).find(".handle-td").append($compile(btnStr)($scope));

            var checkStr = "";
            checkStr += '<input type="checkbox" data-index="' + iDisplayIndex + '" value="' + $scope.myDatas.result[iDisplayIndex].id + '" class="checkchild" />';
            $(nRow).find(".handle-ck").append($compile(checkStr)($scope));
			
			//菜单等级
			var gradeStr = "";
			if(aData.level == 0){
				gradeStr = "一级菜单";
			} else{
				gradeStr = "二级菜单";
			}
            $(nRow).find(".menu-grade").append(gradeStr);
            
            //菜单类型
            var menuType = "";
            if(aData.menuType == "INTERNAL"){
            	menuType = "内部";
            } else{
            	menuType = "外部";
            }
            $(nRow).find(".menuType").append(menuType);
            
            //菜单状态
            var menuStatus = "";
            if(aData.status == "AVAILABLE"){
            	menuStatus = "可用";
            } else if(aData.status == "DELETE"){
            	menuStatus = "删除";
            } else if(aData.status == "FORBID"){
            	menuStatus = "禁止";
            }
            $(nRow).find(".menuStatus").append(menuStatus);
        },
        "fnDrawCallback": function(oSettings) {

        },
        "fnServerParams": function(aoData) {

        },
        "fnServerData": function(sSource, aData, fnCallback, dataTableObject) {
            var upMenuId = "";
            if ($scope.upMenuName != null) {
                upMenuId = $scope.upMenuName.id;
            }

            var obj = dataTableObject.oAjaxData,
                _baseParams = {
                    'page': obj.iDisplayStart / obj.iDisplayLength + 1,
                    'rows': obj.iDisplayLength,
                    'search': 'false',
                    'nd': '1494221804416',
                    // 'rows': 50,
                    // 'page': 1,
                    'order': "asc",
                    'sort': 'sort',
                    //"menuName":obj.sSearch,  //搜索参数 menuName：菜单搜索  tagName：关键字搜索
                    "menuName": $scope.menuName,
                    "upId": upMenuId,
          			'status': $scope.itemStatus.status
                };

            var __data = angular.extend({}, _baseParams, obj.queryParams);
            $scope.__data = __data; //存储参数在所搜的时候要用
            rest.decoJava({
                type: "POST",
                url: "/tenancy-sys/admin/menu/list",
                data: __data,
                //contentType:"application/json",
                beforeSend: function(request) {
                    request.setRequestHeader("token", token);
                },
                success: function(data) {
                    $scope.myDatas = data;
                    $scope.$apply();
                    //渲染datatables
                    var data1 = {
                        'aaData': data.result,
                        'sEcho': obj.sEcho,
                        'iTotalDisplayRecords': data.pager.recordCount,
                        'iTotalRecords': data.records,
                    };
                    fnCallback(data1);
					//$(dataTableObject.nScrollBody).css('overflow', 'visible');
                    //$(dataTableObject.nScrollBody).css('margin-bottom', 60 + 'px');
                    $(".dataTables_scroll").css("overflow", "auto");
        			$(".dataTables_scrollBody").css("overflow", "visible");
                }
            });

            //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
            //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
            $scope.search = function() {
                $scope.__data.menuName = $scope.menuName;
                $scope.__data.upId = $scope.upMenuName.id;
                $scope.__data.page = 1;
                $scope.dataTable.fnClearTable();
            }

        }
    }

    $scope.initFinish = function(dataTable) {
        $scope.dataTable = dataTable;
    }

    //编辑菜单
    $scope.menuedit = function(iDisplayIndex, e) {
        //权限控制
        var nowId = this.btns.edit;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        //var btn = $(e.target);
        ngDialog.openConfirm({
            template: 'js/module/decorate/menuEditor.html',
            resolve: {
                load: function() {
                    return $ocLazyLoad.load('angularFileUpload').then(
                        function() {
                            return uiLoad.load(['js/module/decorate/menuEditor.js'])
                        });
                }
            },
            data: $scope.myDatas.result[iDisplayIndex],
            scope: $scope,
            width: 1200,
        }).then(function(data) {
            $scope.dataTable.fnClearTable();
        }, function(reason) {
            $scope.dataTable.fnClearTable();
        });

    };

    //新建菜单
    $scope.newMenu = function(iDisplayIndex, e) {
        //权限控制
        var nowId = this.btns.add;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        //var btn = $(e.target);
        ngDialog.openConfirm({
            template: 'js/module/decorate/newMenu.html',
            resolve: {
                load: function() {
                    return $ocLazyLoad.load('angularFileUpload').then(
                        function() {
                            return uiLoad.load(['js/module/decorate/newMenu.js'])
                        });
                }
            },
            data: {
                datas: $scope.upMenus
            },
            scope: $scope,
            width: 1200,
            // height: 700
        }).then(function(data) {
            $scope.dataTable.fnClearTable();
        }, function(reason) {
            $scope.dataTable.fnClearTable();
        });
    }

    //全部选中和取消
    $scope.allMenu = function(e) {
        var This = angular.element(e.target);
        if (This.is(":checked")) {
            angular.element(".checkchild").prop("checked", true);
        } else {
            angular.element(".checkchild").prop("checked", false);
        }
    }

    //删除模块、菜单
    $scope.deleteMenu = function(e) {
        //权限控制
        var nowId = this.btns.delete;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 2000, //0不自动关闭
            });
        } else {
            layer.msg("确定删除吗？", {
                offset: 't',
                icon: 3,
                time: 0, //不自动关闭
                btn: ['确定', '取消'],
                yes: function(index) {
                    layer.close(index);

                    //执行删除 数据格式要求 要将数组转换成字符串 并截除最后的逗号
                    var idArr = [];
                    $(".checkchild").each(function() {
                        if ($(this).is(":checked")) {
                            idArr.push($(this).val());
                        }
                    });
                    var _idstring = "";
                    angular.forEach(idArr, function(data) {
                        _idstring += data + ',';
                    })
                    var _idstring = _idstring.substring(0, _idstring.length - 1);

                    //提交
                    var token = $window.localStorage.getItem("token");
                    rest.decoJava({
                        type: 'post',
                        url: '/tenancy-sys/admin/menu/delete',
                        data: {
                            "ids": _idstring
                        },
                        beforeSend: function(request) {
                            request.setRequestHeader("token", token);
                        },
                        success: function(result) {
                            if (result.code == "0000") {
                                layer.msg(result.message, {
                                    offset: 't',
                                    icon: 1,
                                    time: 2000, //不自动关闭
                                });
                                $scope.dataTable.fnClearTable();
                            } else {
                                layer.msg(result.message, {
                                    offset: 't',
                                    icon: 5,
                                    time: 2000, //不自动关闭
                                });
                            }
                        }
                    });
                }
            });
        }
    };

    //顶部编辑
    $scope.menueditTop = function() {
        //权限控制
        var nowId = this.btns.edit;
        if (accessStr.indexOf(nowId) == -1) {
            layer.msg("你没有该操作权限", {
                offset: 't',
                icon: 2
            });
            return false;
        }
        if ($(".checkchild:checked").length == 0) {
            layer.msg("没有选中项", {
                offset: 't',
                icon: 2,
                time: 2000, //不自动关闭
            });
        } else if ($(".checkchild:checked").length >= 2) {
            layer.msg("一次只能编辑一项", {
                offset: 't',
                icon: 2,
                time: 2000, //不自动关闭
            });
        } else {
            var iDisplayIndex = parseInt($(".checkchild:checked").attr("data-index"));
            console.log(iDisplayIndex);
            $scope.menuedit(iDisplayIndex)
        }
    }

});